import React, { useState } from 'react';
import { useCopilotAction, useCopilotReadable,useCoAgent } from '@copilotkit/react-core';

const FileUpload = () => {
  const [file, setFile] = useState(null);
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [uploadStatus, setUploadStatus] = useState('');

  // 让 AI 能够读取当前文件状态
  useCopilotReadable({
    description: "当前选择的文件和已上传的文件列表",
    value: {
      selectedFile: file ? { name: file.name, type: file.type, size: file.size } : null,
      uploadedFiles: uploadedFiles,
      uploadStatus: uploadStatus
    }
  });

  useCoAgent({
        name: "qa_agent",
        initialState: { aggregate: { "kb_id": "kb_agent_1448", "kb_des": "金富科技股份有限公司知识库" } }
    });

  // 使用 useCopilotAction 提供文件上传功能给 AI
  useCopilotAction({
    name: "selectAndUploadFile",
    description: "选择文件并上传，可以处理文本文件、图片、PDF等",
    parameters: [
      {
        name: "fileData",
        type: "string",
        description: "文件的 base64 编码数据",
        required: true,
      },
      {
        name: "fileName",
        type: "string",
        description: "文件名",
        required: true,
      },
      {
        name: "fileType",
        type: "string",
        description: "文件类型",
        required: true,
      }
    ],
    handler: async ({ fileData, fileName, fileType }) => {
      // 处理文件上传逻辑
      setUploadStatus(`AI 正在处理文件: ${fileName}`);
      
      // 这里可以添加实际的文件处理逻辑
      // 例如发送到后端服务器进行进一步处理
      console.log("文件上传处理:", fileName, fileType);
      
      // 模拟处理延迟
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 添加到已上传文件列表
      const newFile = {
        id: Date.now(),
        name: fileName,
        type: fileType,
        uploadedAt: new Date().toLocaleString()
      };
      
      setUploadedFiles(prev => [...prev, newFile]);
      setUploadStatus(`文件 ${fileName} 处理完成`);
    },
  }, []);

  useCopilotAction({
    name: "analyzeFileContent",
    description: "分析已上传文件的内容",
    parameters: [
      {
        name: "fileId",
        type: "number",
        description: "要分析的文件ID",
        required: true,
      }
    ],
    handler: async ({ fileId }) => {
      const file = uploadedFiles.find(f => f.id === fileId);
      if (!file) {
        setUploadStatus("未找到指定的文件");
        return;
      }

      setUploadStatus(`正在分析文件: ${file.name}`);
      console.log("正在分析文件",file.name)
      window.microApp.dispatch({functionName: 'analyzeFileContent',context:`正在分析文件: ${file.name}`,time: Date.now()})
      
      // 模拟文件分析过程
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      setUploadStatus(`已完成对文件 "${file.name}" 的分析。作为演示，我无法提供实际内容分析，但在实际应用中，我可以读取并解释文件内容。`);
      window.microApp.dispatch({functionName: 'analyzeFileContent',context:`已完成对文件 "${file.name}" 的分析。作为演示，我无法提供实际内容分析，但在实际应用中，我可以读取并解释文件内容。`,time: Date.now()})
    },
  }, [uploadedFiles]);

  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];
    if (selectedFile) {
      setFile(selectedFile);
      setUploadStatus(`已选择文件: ${selectedFile.name}`);
    }
  };

  const handleUpload = async () => {
    if (!file) {
      setUploadStatus('请先选择文件');
      return;
    }

    setUploadStatus('正在上传文件...');

    // 将文件转换为 base64 编码
    const reader = new FileReader();
    reader.onload = async (e) => {
      const fileData = e.target.result;
      
      // 添加到已上传文件列表
      const newFile = {
        id: Date.now(),
        name: file.name,
        type: file.type,
        size: file.size,
        uploadedAt: new Date().toLocaleString()
      };
      
      setUploadedFiles(prev => [...prev, newFile]);
      
      console.log("文件上传:", file.name);
      
      setUploadStatus('文件上传成功');
      
      // 重置文件选择
      setFile(null);
      document.getElementById('fileInput').value = '';
    };
    
    reader.readAsDataURL(file);
  };

  const removeFile = (id) => {
    setUploadedFiles(prev => prev.filter(f => f.id !== id));
  };

  return (
    <div style={{ padding: '20px', border: '1px solid #ccc', borderRadius: '5px', margin: '10px 0' }}>
      <h3>文件上传</h3>
      <input 
        id="fileInput"
        type="file" 
        onChange={handleFileChange} 
        accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.csv,.md"
      />
      <button onClick={handleUpload} style={{ marginLeft: '10px' }}>
        上传文件
      </button>
      
      {uploadedFiles.length > 0 && (
        <div style={{ marginTop: '15px' }}>
          <h4>已上传的文件:</h4>
          <ul>
            {uploadedFiles.map((uploadedFile) => (
              <li key={uploadedFile.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>{uploadedFile.name} ({uploadedFile.type.split('/')[1] || 'unknown'})</span>
                <div>
                  <button 
                    onClick={() => removeFile(uploadedFile.id)}
                    style={{ marginLeft: '10px', backgroundColor: '#ff4444', color: 'white', border: 'none', borderRadius: '3px', padding: '3px 8px' }}
                  >
                    删除
                  </button>
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
      
      <div style={{ marginTop: '10px' }}>
        {uploadStatus && <p>{uploadStatus}</p>}
      </div>
      
      <div style={{ marginTop: '15px', padding: '10px', backgroundColor: '#f0f8ff', borderRadius: '5px' }}>
        <h4>AI 助手文件操作说明:</h4>
        <p>您可以要求 AI 助手帮您:</p>
        <ul>
          <li>上传特定的文件</li>
          <li>分析已上传文件的内容</li>
          <li>总结文件的主要信息</li>
          <li>从文件中提取特定数据</li>
        </ul>
      </div>
    </div>
  );
};

export default FileUpload;